define(['jquery', 'bootstrap', 'backend', 'table', 'form'], function ($, undefined, Backend, Table, Form) {

    var Controller = {
        index: function () {
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    index_url: 'goods/goods/index' + location.search,
                    add_url: 'goods/goods/add',
                    edit_url: 'goods/goods/edit',
                    del_url: 'goods/goods/del',
                    multi_url: 'goods/goods/multi',
                    import_url: 'goods/goods/import',
                    table: 'goods',
                }
            });

            var table = $("#table");

            table.on('post-common-search.bs.table', function (event, table) {
                var form = $("form", table.$commonsearch);
                $("input[name='cate_id']", form)
                    .addClass("selectpage")
                    .data("source", "category/selectpagetree")
                    .data("primaryKey", "id")
                    .data("field", "name")
                    .data("orderBy", "id desc");
                Form.events.cxselect(form);
                Form.events.selectpage(form);
            });

            // 初始化表格
            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                pk: 'id',
                sortName: 'id',
                fixedColumns: true,
                fixedRightNumber: 1,
                search: false,
                commonSearch: true,
                searchFormVisible: true,
                columns: [
                    [
                        {checkbox: true},
                        {field: 'id', title: __('Id'), operate: false, sortable: true},
                        {field: 'cate_id', title: __('Cate_id'), visible:false, operate: 'LIKE %...%'},
                        {field: 'category.name', title: __('Cate_id'), operate: false},
                        {field: 'goods_sn', title: __('Goods_sn'), operate: 'LIKE'},
                        {field: 'goods_name', title: __('Goods_name'), operate: 'LIKE',formatter: Table.api.formatter.content},
                        {field: 'image', title: __('Image'), operate: false, events: Table.api.events.image, formatter: Table.api.formatter.image},
                        {field: 'spec_sum', title: __('商品库存'), operate: false},
                        // {field: 'brand', title: __('Brand'), operate: 'LIKE'},
                        // {field: 'images', title: __('Images'), operate: false, events: Table.api.events.image, formatter: Table.api.formatter.images},
                        // {field: 'params', title: __('Params'), operate: false},
                        {field: 'price', title: __('Price'), operate:'BETWEEN', sortable: true},
                        {field: 'is_index', title: __('首页推荐'), operate: false, formatter: Table.api.formatter.toggle},
                        // {field: 'original_price', title: __('Original_price'), operate: false},
                        // {field: 'limit_num', title: __('Limit_num'), operate: false},
                        // {field: 'stock_type', title: __('Stock_type'), searchList: {"place":__('Stock_type place'),"pay":__('Stock_type pay')}, formatter: Table.api.formatter.normal, operate: false},
                        // {field: 'service_ids', title: __('Service_ids'), operate: false},
                        // {field: 'dispatch_type', title: __('Dispatch_type'), operate: false},
                        // {field: 'dispatch_ids', title: __('Dispatch_ids'), operate: false},
                        {field: 'likes', title: __('Likes'), operate: false, sortable: true},
                        {field: 'views', title: __('Views'), operate: false, sortable: true},
                        {field: 'sales', title: __('Sales'), operate: false, sortable: true},
                        {field: 'weigh', title: __('Weigh'), operate: false, sortable: true},
                        {field: 'status', title: __('Status'), searchList: {"up":__('Status up'),"hidden":__('Status hidden'),"down":__('Status down')}, formatter: Table.api.formatter.status},
                        // {field: 'show_sales', title: __('Show_sales'), operate: false},
                        {field: 'createtime', title: __('Createtime'), operate:'RANGE', addclass:'datetimerange', autocomplete:false, formatter: Table.api.formatter.datetime, sortable: true},
                        // {field: 'updatetime', title: __('Updatetime'), operate: false, addclass:'datetimerange', autocomplete:false, formatter: Table.api.formatter.datetime},
                        {field: 'operate', title: __('Operate'), table: table, events: Table.api.events.operate, formatter: Table.api.formatter.operate}
                    ]
                ]
            });

            // 为表格绑定事件
            Table.api.bindevent(table);
        },
        recyclebin: function () {
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    'dragsort_url': ''
                }
            });

            var table = $("#table");

            // 初始化表格
            table.bootstrapTable({
                url: 'goods/goods/recyclebin' + location.search,
                pk: 'id',
                sortName: 'id',
                columns: [
                    [
                        {checkbox: true},
                        {field: 'id', title: __('Id')},
                        {
                            field: 'deletetime',
                            title: __('Deletetime'),
                            operate: 'RANGE',
                            addclass: 'datetimerange',
                            formatter: Table.api.formatter.datetime
                        },
                        {
                            field: 'operate',
                            width: '130px',
                            title: __('Operate'),
                            table: table,
                            events: Table.api.events.operate,
                            buttons: [
                                {
                                    name: 'Restore',
                                    text: __('Restore'),
                                    classname: 'btn btn-xs btn-info btn-ajax btn-restoreit',
                                    icon: 'fa fa-rotate-left',
                                    url: 'goods/goods/restore',
                                    refresh: true
                                },
                                {
                                    name: 'Destroy',
                                    text: __('Destroy'),
                                    classname: 'btn btn-xs btn-danger btn-ajax btn-destroyit',
                                    icon: 'fa fa-times',
                                    url: 'goods/goods/destroy',
                                    refresh: true
                                }
                            ],
                            formatter: Table.api.formatter.operate
                        }
                    ]
                ]
            });

            // 为表格绑定事件
            Table.api.bindevent(table);
        },

        add: function () {
            Controller.api.bindevent();
        },
        edit: function () {
            ajaxGetSpecInput();
            Controller.api.bindevent();
        },
        api: {
            bindevent: function () {
                Form.api.bindevent($("form[role=form]"));
            }
        }
    };

    $(function () {
        $(document).on("click", '.delete_item', function (e) {
            if ($(this).text() == '禁用') {
                // $(this).parent().parent().find('input').removeAttr('disabled');
                $(this).next().val(0);
                $(this).addClass('btn-info');
                $(this).removeClass('btn-danger');
                $(this).text('启用');
            } else {
                $(this).next().val(1);
                $(this).addClass('btn-danger');
                $(this).removeClass('btn-info');
                $(this).text('禁用');
                // $(this).parent().parent().find('input').attr('disabled', 'disabled');
            }
        })
        // 规格按钮切换 class
        $(".spec").click(function(){
            if($(this).hasClass('btn-success'))
            {
                $(this).removeClass('btn-success');
                $(this).addClass('btn-default');
            }else{
                $(this).removeClass('btn-default');
                $(this).addClass('btn-success');
            }
            ajaxGetSpecInput();
        });
    })

    /**
     *  点击商品规格触发下面输入框显示
     */
    function ajaxGetSpecInput() {
        var spec_arr = {};// 用户选择的规格数组
        // 选中了哪些属性
        $("#goods_spec_table1  button").each(function () {
            if ($(this).hasClass('btn-success')) {
                var spec_id = $(this).data('spec_id');
                var item_id = $(this).data('item_id');
                if (!spec_arr.hasOwnProperty(spec_id))
                    spec_arr[spec_id] = [];
                spec_arr[spec_id].push(item_id);
            }
        });

        ajaxGetSpecInput2(spec_arr); // 显示下面的输入框
    }

    /**
     * 根据用户选择的不同规格选项
     * 返回 不同的输入框选项
     */
    function ajaxGetSpecInput2(spec_arr) {

        var goods_id = $("input[name='goods_id']").val();
        // var goods_id = "{$goods_id}";
        $.ajax({
            type: 'POST',
            data: {spec_arr: spec_arr, goods_id: goods_id},
            url: "goods/goods/ajaxGetSpecInput",
            success: function (data) {
                $("#goods_spec_table2").html('').append(data);

                hbdyg();  // 合并单元格

                Form.events.plupload($("form[role=form]"));//动态绑定上传按钮
                Form.events.faselect($("form[role=form]"));//动态绑定选择附件按钮

                $('.p-spec_image .col-xs-3').removeClass('col-xs-3').addClass('col-xs-12');
            }
        });

    }

    // 合并单元格
    function hbdyg() {
        var tab = document.getElementById("spec_input_tab"); //要合并的tableID
        var maxCol = 2, val, count, start;  //maxCol：合并单元格作用到多少列
        if (tab != null) {
            for (var col = maxCol - 1; col >= 0; col--) {
                count = 1;
                val = "";
                for (var i = 0; i < tab.rows.length; i++) {
                    if (val == tab.rows[i].cells[col].innerHTML) {
                        count++;
                    } else {
                        if (count > 1) { //合并
                            start = i - count;
                            tab.rows[start].cells[col].rowSpan = count;
                            for (var j = start + 1; j < i; j++) {
                                tab.rows[j].cells[col].style.display = "none";
                            }
                            count = 1;
                        }
                        val = tab.rows[i].cells[col].innerHTML;
                    }
                }
                if (count > 1) { //合并，最后几行相同的情况下
                    start = i - count;
                    tab.rows[start].cells[col].rowSpan = count;
                    for (var j = start + 1; j < i; j++) {
                        tab.rows[j].cells[col].style.display = "none";
                    }
                }
            }
        }
    }

    return Controller;
});
